<?php

namespace app\storeapi\model\card;

use app\common\model\card\Card as CardModel;



/**
 * 整点秒杀-商品模型
 * Class Goods
 * @package app\store\model\sharp
 */
class Card extends CardModel
{
    /**
     * 获取列表数据
     * @param string $search
     * @return mixed|\think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cardList()
    {
        $list = $this->with(['image'])
            ->where(['is_delete'=>0])
            ->select();
        return $list;
    }

    /**
     * 添加储值卡
     * @param string $search
     * @return mixed|\think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add($param)
    {
        // 表单验证
        if (!$this->validateCard($param)) return false;
        // 添加商品
        return $this->allowField(true)->save(array_merge($param,['wxapp_id'=>self::$wxapp_id]));

    }

    /**
     * 编辑储值卡
     * @param string $search
     * @return mixed|\think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($param)
    {
        // 表单验证
        if (!$this->validateCard($param)) return false;

        return $this->allowField(true)->save($param);
    }


    /**
     * 验证储值卡
     * @param $goodsId
     * @return bool
     */
    public function validateCard($param)
    {
        if(!isset($param['image_id']) || empty($param['image_id'])){
            $this->error = '请上传图片';
            return false;
        }
        if(!isset($param['card_title']) || empty($param['card_title'])){
            $this->error = '请输入储值卡名称';
            return false;
        }

        return true;
    }

    /**
     * 商品ID是否存在
     * @param $goodsId
     * @return bool
     */
    public static function isExistCard()
    {
        return  !!(new static)->where('wxapp_id', '=', self::$wxapp_id)->find();
    }


    /**
     * 删除储值卡
     * @param string $search
     * @return mixed|\think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setDelete()
    {
        return $this->allowField(true)->save(['is_delete' => 1]);
    }

}